﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TimeTracker_BL.Repositories;
using Telerik.Web.Mvc;
using TimeTracker_Entities;
using TimeTracker.Models;


namespace TimeTracker.Controllers
{
    [Authorize()]
    public class TimeEntryController : Controller
    {
        private ITimeTrackerRepository _db;
        private ILookupsRepository _lookups;

        /// <summary>
        /// Initializes a new instance of the <see cref="TimeEntryController"/> class.
        /// </summary>
        public TimeEntryController()
        {
            _db = new TimeTrackerRepository();
            _lookups = new LookupsRepository();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TimeEntryController"/> class.
        /// </summary>
        /// <param name="db">The entity db.</param>
        /// <param name="lookups">The lookups database.</param>
        public TimeEntryController(ITimeTrackerRepository db, ILookupsRepository lookups)
        {
            _db = db;
            _lookups = lookups;
        }

        public ActionResult Index()
        {
            PopulateClientsLookup();
            PopulateProjectsLookup();

            return View();
        }

        [GridAction]
        public ActionResult _GetTimeEntries()
        {
            // Get a list of all time entries
            var entries = (from e in _db.GetAllTimeEntries()
                           orderby e.DateWorked descending, e.FromTime descending
                           where e.DateWorked >= DateTime.Now.AddDays(-45)
                                && e.CreatedBy.Equals(User.Identity.Name, StringComparison.CurrentCultureIgnoreCase)
                          select new TimeEntryModel(e)).ToList<TimeEntryModel>();
                         
            return View(new GridModel<TimeEntryModel>(entries));
        }

        [GridAction]
        public ActionResult _AddTimeEntry(TimeEntryModel entryToAdd)
        {
            // Add the time entry to the database
            var result = _db.AddEntry(entryToAdd.ToEntity(), User.Identity.Name);

            // Return either the updated list or an error message
            if (result.IsSuccessful)
            {
                return _GetTimeEntries();
            }
            else
            {
                return Content(result.ErrorMessage);
            }
        }

        [GridAction]
        public ActionResult _UpdateTimeEntry(TimeEntryModel updatedEntry)
        {
            // Update the time entry in the database
            var result = _db.UpdateEntry(updatedEntry.ToEntity());

            // Return either the updated list or an error message
            if (result.IsSuccessful)
            {
                return _GetTimeEntries();
            }
            else
            {
                return Content(result.ErrorMessage);
            }
        }

        [GridAction]
        public ActionResult _DeleteTimeEntry(int id)
        {
            // Delete the time entry from the database
            var result = _db.DeleteEntry(id);

            // Return either the updated list or an error message
            if (result.IsSuccessful)
            {
                return _GetTimeEntries();
            }
            else
            {
                return Content(result.ErrorMessage);
            }
        }

        /// <summary>
        /// Displays the report.
        /// </summary>
        public ActionResult WeeklyRevenueReport()
        {
            // Get the time entries for the month
            var firstDayOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
            var allEntries = _db.GetAllTimeEntriesBetween(firstDayOfMonth, lastDayOfMonth);

            // Get the total for the month
            ViewData["RevenueCurrentMonthToDate"] = allEntries.Sum(e => e.TotalRevenue);

            return View();
        }

        /// <summary>
        /// Selects the report data.
        /// </summary>
        /// <param name="fromDate">From date.</param>
        /// <param name="toDate">To date.</param>
        public ActionResult _SelectWeeklyRevenueReportData(DateTime fromDate, DateTime toDate){
            
            // Get the data for the chart
            var entryReports = from e in _db.GetAllTimeEntriesBetween(fromDate, toDate)
                               select new TimeEntryReport(e);

            return Json(entryReports);
        }

        #region Private Helpers
        /// <summary>
        /// Populates the clients lookup.
        /// </summary>
        private void PopulateClientsLookup()
        {
            ViewBag.Clients = _db.GetClients();
        }

        /// <summary>
        /// Populates the projects lookup.
        /// </summary>
        private void PopulateProjectsLookup()
        {
            ViewBag.Projects = from p in _db.GetProjects()
                               orderby p.Client.ClientName, p.ProjectName
                               select new ProjectDropDownDisplay(p);
        }
        #endregion
    }
}
